package com.wellsoft.pt.app.dingtalk.job;

import java.util.List;

import org.apache.commons.collections4.CollectionUtils;
import org.quartz.JobExecutionContext;

import com.dingtalk.api.request.OapiWorkrecordAddRequest.FormItemVo;
import com.wellsoft.context.jdbc.support.PagingInfo;
import com.wellsoft.context.util.ApplicationContextHolder;
import com.wellsoft.pt.app.dingtalk.entity.WorkRecord;
import com.wellsoft.pt.app.dingtalk.service.WorkRecordService;
import com.wellsoft.pt.app.dingtalk.utils.DingtalkApiUtils;
import com.wellsoft.pt.task.job.Job;
import com.wellsoft.pt.task.job.JobData;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * Description: 定时钉钉事件回调任务 钉钉事件回调，解析结果数据，落地数据到对应数据表
 *  
 * @author Well
 * @date 2020年5月29日
 * @version 1.0
 * 
 * <pre>
 * 修改记录:
 * 修改后版本	修改人		修改日期			修改内容
 * 2020年5月29日.1	Well		2020年5月29日		Create
 * </pre>
 *
 */
public class DingtalkWorkRecordJob extends Job {

	@SuppressWarnings({ "deprecation", "unchecked" })
	@Override
	protected void execute(JobExecutionContext arg0, JobData arg1) {
		String accessToken = DingtalkApiUtils.getAccessToken();
		WorkRecordService workRecordService = ApplicationContextHolder.getBean(WorkRecordService.class);
		PagingInfo page = new PagingInfo(0, 10); // 每次10条
		List<WorkRecord> list = workRecordService.listByNameHQLQueryAndPage("getWorkRecordByPage", null, page);
		if (CollectionUtils.isNotEmpty(list)) {
			for (WorkRecord record : list) {
				int status = record.getRecordStatus();
				JSONObject jb = null;
				if (status == 1) {
					JSONArray items = JSONArray.fromObject(record.getFormItemList());
					List<FormItemVo> formitems = JSONArray.toList(items, FormItemVo.class);
					jb = DingtalkApiUtils.addWorkRecord(record.getBizId(), record.getDingUserId(), record.getUserName(),
							accessToken, record.getTitle(), record.getUrl(), formitems);
				} else if (status == 2) {
					jb = DingtalkApiUtils.updateWorkRecord(record.getBizId(), record.getDingUserId(), accessToken);
				}
				if (jb != null) { // 标识调取接口成功，移除数据库错误数据
					// workRecordService.delete(record);
				}
			}
		}
	}
}
